package com.drondea.testclient.service;

import cn.hutool.core.collection.CollectionUtil;
import com.drondea.sms.channel.ChannelSession;
import com.drondea.sms.message.IMessage;
import com.drondea.sms.message.cmpp.CmppSubmitRequestMessage;
import com.drondea.sms.thirdparty.SmsAlphabet;
import com.drondea.sms.thirdparty.SmsDcs;
import com.drondea.sms.type.IMessageResponseHandler;
import com.drondea.testclient.panel.CmppPanel;
import com.drondea.testclient.service.provider.CmppClientMessageProvider;
import com.drondea.testclient.util.CommonThreadPoolFactory;
import com.drondea.testclient.util.counter.CmppAtomicUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 发送服务类 2
 *
 * @author sun
 * 2019年4月23日 下午2:25:34
 */

@Slf4j
public class CmppService extends AbstractTcpService {

    private static final CmppPanel PANEL = CmppPanel.getInstance();
    private static final CmppService INSTANCE = new CmppService();
    
    private CmppService() {}
    public static CmppService getInstance() {
        return INSTANCE;
    }

    @Override
    public void sendSms(String mobile, String content, String subCode) {
        try {
            CmppSubmitRequestMessage requestMessage = new CmppSubmitRequestMessage();
            requestMessage.setMsgContent(content);
            requestMessage.setServiceId(PANEL.serviceIdTextField.getText());
            requestMessage.setMsgSrc(PANEL.msgSrcTextField.getText());
            // 扩展码
            requestMessage.setSrcId(subCode);
            requestMessage.setRegisteredDelivery((short) 1);
            requestMessage.setDestUsrTl((short) 1);
            requestMessage.setDestTerminalId(new String[]{mobile});
            requestMessage.setMsgFmt(SmsDcs.getGeneralDataCodingDcs(SmsAlphabet.RESERVED));
            requestMessage.setMessageResponseHandler(new IMessageResponseHandler() {

                @Override
                public void messageComplete(IMessage requestMsg, IMessage responseMsg) {
                    log.debug("messageComplete");
                    CmppAtomicUtil.handlerDelay(System.currentTimeMillis() - requestMsg.getSendTimeStamp());
                }

                @Override
                public void messageExpired(String s, IMessage iMessage) {
                    log.error("messageExpired");
                    CmppAtomicUtil.handlerDelay(System.currentTimeMillis() - iMessage.getSendTimeStamp());
                }

                @Override
                public void sendMessageFailed(IMessage iMessage) {
                    CmppAtomicUtil.handlerDelay(System.currentTimeMillis() - iMessage.getSendTimeStamp());
                    log.error("sendMessageFailed");
                }
            });
            log.debug("requestMessage = {}", requestMessage);
            sendMessage(requestMessage);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    private void sendMessage(CmppSubmitRequestMessage requestMessage) {
        List<ChannelSession> sessions = PANEL.sessionManager.getSessions();
        if (CollectionUtil.isEmpty(sessions)) {
            log.error("ChannelSession为空，无法发送短信");
            return;
        }
        CmppClientMessageProvider messageProvider = (CmppClientMessageProvider) PANEL.sessionManager.getMessageProvider();
        boolean hasSend = messageProvider.addMessage(requestMessage);
        if (!hasSend) {
            resendMessageDelay(requestMessage, 1000);
        }
    }

    public void resendMessageDelay(CmppSubmitRequestMessage requestMessage, int delay) {
        CommonThreadPoolFactory.getInstance().getScheduleExecutor().schedule(() -> {
            sendMessage(requestMessage);
        }, delay, TimeUnit.MILLISECONDS);
    }

}
